package com.hqbzl.c1.rlock;

import com.hqbzl.c1.TestBigRoom;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

// 要求t2要在t1之后执行
@Slf4j
public class ThreadPattern2 {
    static final ReentrantLock ROOM = new ReentrantLock();
    static final Condition t2 = ROOM.newCondition();
    static boolean t2runafter = false;

    public static void main(String[] args) {


        final Thread t1 = new Thread(() -> {
            ROOM.lock();
            try {
                log.debug("wait t2 run");
                try {
                    while (!t2runafter) {
                        t2.await();
                    }
                    // 需要条件检查 ，防止选通后后阴塞的情况
                    //       t2.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                log.debug("t1 run");
            } finally {
                ROOM.unlock();
            }
        }, "t1");

        final Thread t2 = new Thread(() -> {
            ROOM.lock();
            try {
                log.debug("t2 run");
                t2runafter = true;
                ThreadPattern2.t2.signal();
            } finally {
                ROOM.unlock();
            }
        }, "t2");
        t2.start();
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        t1.start();

    }

}
